#!/bin/bash

set -e

cd "$(dirname "$0")"

function read_me() {
    echo "rabbitmq: 5677, rabbitmq manage ui: 5678, user: dev, password: qwe123"
    echo "mysql: 3041, user: dev, password: qwe123, db-adminer: 8041"
}

function setup_rabbitmq {
  echo "install rabbitmq..."
  docker-compose -f ./docker-compose.yml up -d yuanyuan-rabbitmq
  echo "finish exc install rabbitmq."
}

function setup_mysql {
  echo "install mysql... "
  docker-compose -f ./docker-compose.yml up -d yuanyuan-mysql
  echo "finish exc install mysql."

  echo "install db adminer..."
  docker-compose -f ./docker-compose.yml up -d yuanyuan-db-adminer
  echo "finish exc install adminer."
}

function init_db {
  echo "init db..."
  export DB_HOST="127.0.0.1"
  export DB_PORT="3041"
  export DB_NAME="mq-platform"
  export DB_USERNAME="dev"
  export DB_PASSWORD="qwe123"

  init-db/init-db.sh
}

func=(read_me setup_rabbitmq setup_mysql init_db)

function do_command () {
    case $1 in
        read_me)
            read_me
            ;;
        setup_rabbitmq)
            setup_rabbitmq
            ;;
        setup_mysql)
            setup_mysql
            ;;
        init_db)
            init_db
            ;;
        *)
            echo "No command matched here."
            ;;
    esac
}

function in_array () {
    TARGET=$1
    shift 1
    for ELEMENT in "$@"
    do
        if [[ "$TARGET" == "$ELEMENT" ]]
        then
            echo 0
            return 0
        fi
    done
    echo 1
    return 1
}

function select_cmd () {
    echo "Please select what you want to do:"
    select CMD in ${func[*]}
    do
        if [[  $(in_array "$CMD" "${func[@]}") = 0 ]]
        then
            do_command "$CMD"
            break
        fi
    done
}

function main () {
    if [[ $1 != "" && $(in_array "$1" "${func[*]}") = 0 ]]
    then
        do_command "$*"
    else
        select_cmd
    fi
}

main "$*"